#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <memory>
#include <unistd.h>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{

    using namespace log_ns;
    class Socket; // 声明Socket类
    using SockSPtr = std::shared_ptr<Socket>;
    const static int gblcklog = 8;

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;                                     // 创建套接字
        virtual void CreateBindOrDie(uint16_t port) = 0;                          // 绑定套接字
        virtual void CreateListenOrDie(int backlog = gblcklog) = 0;               // 监听
        virtual SockSPtr Accepter(InetAddr *cliaddr) = 0;                         // 服务端获取连接
        virtual bool Conntecor(const std::string &peerip, uint16_t peerport) = 0; // 客户端连接服务端
        virtual int Sockfd() = 0;                                                 // 获取套接字
        virtual void Close() = 0;                                                 // 关闭套接字

        virtual ssize_t Recv(std::string *out) = 0;      // 读取数据
        virtual ssize_t Send(const std::string &in) = 0; // 发送数据

        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();         // 创建套接字
            CreateBindOrDie(port);       // 绑定套接字
            CreateListenOrDie(gblcklog); // 监听
        }

        bool BuildClientSocket(const std::string &peerip, uint16_t peerport)
        {
            CreateSocketOrDie();
            return Conntecor(peerip, peerport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket() {}
        TcpSocket(int sockfd) : _sockfd(sockfd) {}
        ~TcpSocket() {}
        void CreateSocketOrDie() override // 创建套接字
        {
            // 1.创建sockfd
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "sockfd create error\n");
                exit(1);
            }
            LOG(INFO, "sockfd create success,sockfd:%d\n", _sockfd);
        }

        void CreateBindOrDie(uint16_t port) override // 绑定套接字
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY; // 任意主机
            // 2.绑定套接字
            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(1);
            }
            LOG(DEBUG, "bind success\n");
        }

        void CreateListenOrDie(int backlog = gblcklog)
        {
            // 3.建立监听
            int listenfd = listen(_sockfd, backlog);
            if (listenfd < 0)
            {
                LOG(FATAL, "listenfd create error\n");
                exit(1);
            }
            LOG(DEBUG, "listenfd create success\n");
        }

        SockSPtr Accepter(InetAddr *cliaddr) // 服务端获取客户端的连接,返回客户端的IP和端口信息
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 4.获取新连接
            int sockfd = accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            *cliaddr = InetAddr(client);

            LOG(DEBUG, "get a new link,client info :%s,sockfd is:%d\n", cliaddr->AddrStr().c_str(), sockfd);
            return std::make_shared<TcpSocket>(sockfd);
        }
        bool Conntecor(const std::string &peerip, uint16_t peerport) // 客户端连接服务端
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            return true;
        }
        int Sockfd()
        {
            return _sockfd;
        }

        void Close()
        {
            if (_sockfd > 0)
                close(_sockfd);
        }
        ssize_t Recv(std::string *out)
        {
            char buff[4096];
            ssize_t n = recv(_sockfd, buff, sizeof(buff) - 1, 0);
            if (n > 0)
            {
                buff[n] = 0;
                *out += buff;
            }
            return n;
        }
        ssize_t Send(const std::string &in)
        {
            return send(_sockfd, in.c_str(), in.size(), 0);
        }

    private:
        int _sockfd; // 可以是监听套接字，也可以是连接套接字
    };

};